import 'dart:collection';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:group_button/group_button.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/LjgmOrder.dart';

import 'Login.dart';

/**
 * 服务预约页面
 */
class YuYueService extends StatefulWidget {
  String gid;  //服务ID
  String gName;//服务名称
  String merchantId;//店铺ID
  YuYueService({Key key, this.gid, this.gName, this.merchantId}) : super(key: key);

  @override
  _YuYueService createState() => _YuYueService(gid,gName,merchantId);
}

class _YuYueService extends State<YuYueService> {

  String gid;         //服务ID
  String gName;       //服务名称
  String userId;      //用户ID
  bool isLogin;       //用户是否登录
  String merchantId;  //商户ID
  List jishiList = [];//商户技师集合
  String yuyueRiqi;   //预约日期
  String yuyueTime;   //预约时间

  TextEditingController _nick = new TextEditingController(); // 文本框控制器
  TextEditingController _phone = new TextEditingController();
  TextEditingController _renshu = new TextEditingController();
  TextEditingController _beizhu = new TextEditingController();
  // 构造方法
  _YuYueService(gid,gName,merchantId) {
    this.gid=gid;
    this.gName=gName;
    this.merchantId=merchantId;
    _onLoading();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }
  // 获取数据
  void _onLoading() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    isLogin = prefs.getBool("isLogin");
    // merchantId = prefs.getString("merchantID");
    var x = await HttpUtil().get("/waimai/merchantJishi/getJishiByMercahnt?mId="+merchantId);
    if(x['code']==200){
      jishiList = x['data'];
    }
    // yuyueRiqi = new DateTime.now().toString();
    DateTime today = new DateTime.now();
    yuyueRiqi = "${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
    yuyueTime = "${today.hour.toString()}:${today.minute.toString().padLeft(2,'0')}:${today.second.toString().padLeft(2,'0')}";
    // print("当前日期："+yuyueRiqi+" 当前时间："+yuyueTime);
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return new Scaffold(
      appBar: AppBar(
        title: Text("服务预约"),
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.all(10),
                child: ListView(
                  children: [
                    Row(
                      children: [
                        Text("称呼："),
                        SizedBox(width: 20,),
                        Expanded(child: TextFormField(
                          controller: _nick,
                        )),
                      ],
                    ),
                    Row(
                      children: [
                        Text("电话："),
                        SizedBox(width: 20,),
                        Expanded(child: TextFormField(
                          controller: _phone,
                        )),
                      ],
                    ),Row(
                      children: [
                        Text("人数："),
                        SizedBox(width: 20,),
                        Expanded(child: TextFormField(
                          controller: _renshu,
                        )),
                      ],
                    ),
                    SizedBox(height: 10,),
                    Row(
                      children: [
                        Text("项目："),
                        SizedBox(width: 20,),
                        Expanded(
                          child: Text(gName),
                            // child: DropdownButton(
                            //     hint: Text("请选择预约项目"),
                            //     value: '足浴',
                            //     items: [DropdownMenuItem(child: Text('足浴'),value: "足浴",),
                            //           DropdownMenuItem(child: Text('桑拿'),value: '桑拿',),
                            //           DropdownMenuItem(child: Text('按摩'),value: '按摩',)
                            //       ],
                            //     isExpanded: true,
                            //     onChanged: (value) {
                            //       print(value);
                            //       setState(() {
                            //         // goodsTypeName=value;
                            //       });
                            //     }
                            // )
                        )
                      ],
                    ),
                    Row(
                      children: [
                        Text("日期："),
                        SizedBox(width: 20,),
                        Expanded(child: GestureDetector(
                          child: Container(
                            padding: EdgeInsets.symmetric(vertical: 15),
                            // child: Text(DateTime.now().toString()),
                            child: Text(yuyueRiqi==null ? "" : yuyueRiqi),
                            decoration: BoxDecoration( border: Border(bottom: BorderSide(width: 1,color: Colors.black12)) ,),
                          ),
                          onTap: () async{
                            var result = await showDatePicker(
                              context: context,
                              initialDate: DateTime.now(),
                              firstDate: DateTime.now(),
                              lastDate: DateTime(2030)
                            );
                            yuyueRiqi = "${result.year.toString()}-${result.month.toString().padLeft(2,'0')}-${result.day.toString().padLeft(2,'0')}";
                            setState(() {

                            });
                          },
                        )
                        ),
                      ],
                    ),
                    Row(
                      children: [
                      Text("时间："),
                      SizedBox(width: 20,),
                      Expanded(child: GestureDetector(
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 15),
                          // child: Text(TimeOfDay.now().toString()),
                          child: Text(yuyueTime==null ? "" : yuyueTime),
                          decoration: BoxDecoration( border: Border(bottom: BorderSide(width: 1,color: Colors.black12)) ,),
                        ),
                        onTap: () async{
                          var result = await showTimePicker(
                              context: context,
                              initialTime: TimeOfDay.now()
                          );
                          String dateSlug ="${result.hour.toString().padLeft(2,'0')}:${result.minute.toString().padLeft(2,'0')}:00";
                          yuyueTime = dateSlug;
                          setState(() {

                          });
                        },
                      )),
                    ],
                  ),Row(
                    children: [
                      Text("备注："),
                      SizedBox(width: 20,),
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            // border: Border.all(color: Colors.black54 , width: 1) ,
                            // color: Colors.white,
                          ),
                          child: TextFormField(
                            controller: _beizhu,
                            maxLines: 2,
                            decoration: InputDecoration(
                              hintText: "输入预约备注",
                              hintStyle: TextStyle(fontSize: 14)
                            ),
                          ),
                        )
                      ),
                    ],
                  )
                ],
              )
            )
          ),
          Row(
            children: [
              Expanded(
                child:GestureDetector(
                  child: Container(
                    width: ScreenUtil().setWidth(290),
                    height: ScreenUtil().setHeight(50),
                    child: Center(
                        child: Text(
                          "确定",
                          style: TextStyle(color: Colors.white),
                        )),
                    decoration: BoxDecoration(color: Colors.red),
                  ),
                  onTap: () async {
                    if (!isLogin) {
                      Fluttertoast.showToast(msg: "请先登录");
                      Future.delayed(Duration(seconds: 2), () {
                        MyRoute.replace(Login());
                      });
                    } else {
                      String nick = _nick.text.trim();//用户昵称
                      String phone = _phone.text.trim();//联系电话
                      String num = _renshu.text.trim();//人数
                      String beizhu = _beizhu.text.trim();//预约备注
                      if(nick.length<1){Fluttertoast.showToast(msg: "称呼不能为空");return ;}
                      if(phone.length<1){Fluttertoast.showToast(msg: "电话不能为空");return ;}
                      final zhengshu = RegExp(r'^[+]{0,1}(\d+)$');// 验证是否为正整数
                      if(!zhengshu.hasMatch(num)){Fluttertoast.showToast(msg: "人数只能为正整数");return ;}
                      if(int.parse(num) < 1){Fluttertoast.showToast(msg: "人数需大于0");return;}
                      // print("用户ID："+userId+" 预约服务ID："+gid+" 预约服务名称："+gName+" 昵称："+nick+" 电话："+phone+" 人数："+num);
                      // print("预约日期："+yuyueRiqi+" 预约时间："+yuyueTime);
                      // print("时间："+yuyueRiqi+" "+yuyueTime);
                      var map = new HashMap<String,dynamic>();
                      map['yuyueTime']=yuyueRiqi+" "+yuyueTime;map['nick']=nick;map['phone']=phone;map['num']=num;map['beizhu']=beizhu;
                      map['yuyuexiangmu']=gid;map['yuyuejishi']="0";map['userId']=userId;map['merchantId']=merchantId;map['status']=0;
                      Response response = await HttpUtil().post("waimai/merchantYuyue/addMerchantYuyue",map);
                      var x = json.decode(response.toString());
                      if(x['code']==200){
                        Fluttertoast.showToast(
                            msg: "预约成功"
                        );
                        MyRoute.pop();
                      }else{
                        Fluttertoast.showToast(
                            msg: x['msg']
                        );
                      }
                      // MyRoute.push(LjgmOrder(gid: gid, names: guiges, params: guigexiabiao));
                    }
                  },
                )
              )
            ],
          )
        ],
      )
    );
  }

  // Widget _swiperBuilder(BuildContext context, int index) {
  //   return (CachedNetworkImage(
  //     imageUrl: _imageUrls[index],
  //     fit: BoxFit.fill,
  //   ));
  // }

  // Set selectGuige=new Set(); // 选择的规格
  // var map = new Map();//选择的规格
  //显示规格
  // Widget _showGuige(aaa) {
  //   return StatefulBuilder(builder: (context1, setBottomSheetState) {
  //     funCb = setBottomSheetState;
  //     return Container(
  //       height: 350.0,
  //       child: Column(
  //         children: [
  //           Text("请选择规格"),
  //           Divider(),
  //           Container(
  //             child: Row(
  //               children: [
  //                 CachedNetworkImage(
  //                   imageUrl: Config.getInstance().getHost() + obj['gimages'],
  //                   width: 60,
  //                   height: 60,
  //                 ),
  //                 Column(
  //                   children: [
  //                     // Text("￥${obj['gprice']}"),
  //                     Text("￥${money}"),
  //                   ],
  //                 ),
  //               ],
  //             ),
  //           ),
  //           _showGuigeDetail(),
  //           Expanded(
  //               child: Stack(
  //                 children: [
  //                   Positioned(
  //                     bottom: 0,
  //                     left: ScreenUtil().setWidth(180),
  //                     child: GestureDetector(
  //                       child: Center(
  //                         child: Container(
  //                           child: Text("确定"),
  //                           padding: EdgeInsets.symmetric(vertical: 10,horizontal: 30),
  //                           decoration: BoxDecoration(color: Colors.orangeAccent),
  //                         ),
  //                       ),
  //                       onTap: () async {
  //                         // setBottomSheetState(() {
  //                         //   // 此句代码可用更新选择的规格价格
  //                         // });
  //                         // print("点击了确定");
  //                         int n = guige['select_guiges'].length;
  //                         int m = names.length;
  //                         if (m < n) {
  //                           Fluttertoast.showToast(msg: "请选择完整规格");
  //                           return;
  //                         }
  //                         params = params.sublist(params.length - n);
  //                         names = names.sublist(names.length - n);
  //                         if (m > 1) {
  //                           //排序
  //                           for (int i = 0;
  //                           i < guige['select_guiges'].length;
  //                           i++) {
  //                             if (guige['select_guiges'][i]['name'] != panduan[i]) {
  //                               for (int e = 0; e < panduan.length; e++) {
  //                                 if (guige['select_guiges'][i]['name'] ==
  //                                     panduan[e]) {
  //                                   var z = panduan[i];
  //                                   panduan[i] = panduan[e];
  //                                   panduan[e] = z;
  //                                   var y = names[i];
  //                                   names[i] = names[e];
  //                                   names[e] = y;
  //                                   var o = params[i];
  //                                   params[i] = params[e];
  //                                   params[e] = o;
  //                                 }
  //                               }
  //                             }
  //                           }
  //                         }
  //                         if (params.length == 1) {
  //                           money =
  //                               double.parse(guige['values'][params[0]]['jiage']);
  //                         } else if (params.length == 2) {
  //                           money = double.parse(guige['values'][params[0]]
  //                           ['children'][params[1]]['jiage']);
  //                         } else {
  //                           money = double.parse(guige['values'][params[0]]
  //                           ['children'][params[1]]['children'][params[2]]
  //                           ['jiage']);
  //                         }
  //                         // guiges = names.toString();//规格
  //                         // guigexiabiao = params.toString();//规格下标
  //                         // print("规格："+guiges);
  //                         // print("规格下标："+guigexiabiao);
  //                         // guiges = guiges.substring(1,guiges.length-1);
  //                         // guigexiabiao = guigexiabiao.substring(1,guigexiabiao.length-1);
  //                         guiges = json.encode(names);
  //                         guigexiabiao = json.encode(params);
  //                         // print("规格："+guiges);
  //                         // print("规格下标："+guigexiabiao);
  //                         if (aaa == 1) {
  //                           // print("规格价格："+money.toString());
  //                           var x = await HttpUtil().get(
  //                               "/app/shopCat/addGoodscat?gid=" +
  //                                   "${obj['gid']}" +
  //                                   "&userId=" +
  //                                   userId +
  //                                   "&catnum=1" +
  //                                   "&names=" +
  //                                   guiges +
  //                                   "&params=" +
  //                                   guigexiabiao +
  //                                   "&money=" +
  //                                   money.toString());
  //                           if (x['code'] == 200) {
  //                             Fluttertoast.showToast(msg: "加入购物车成功");
  //                           } else {
  //                             Fluttertoast.showToast(msg: x['msg']);
  //                           }
  //                           // print(params);
  //                           // print(names);
  //                           // print(panduan);
  //                           // var x = selectGuige.toSet();
  //                           // print(x);
  //                           Navigator.pop(context); // 隐藏底部规格选择
  //                           names = [];
  //                           params = [];
  //                           panduan = [];
  //                         } else {
  //                           String gid = obj['gid'];
  //                           MyRoute.push(LjgmOrder(
  //                               gid: gid,
  //                               names: guiges,
  //                               params: guigexiabiao,
  //                               money: money));
  //                         }
  //                       },
  //                     ),
  //                   )
  //                 ],
  //               ))
  //         ],
  //       ),
  //     );
  //   });
  // }

  // 循环显示规格界面中的参数
  // Widget _showGuigeDetail() {
  //   // names = [];
  //   // params = [];
  //   // panduan = [];
  //   List<Widget> col = [];
  //   // print(guige);
  //   // print(guige['select_guiges']);
  //   for (var i = 0; i < guige['select_guiges'].length; i++) {
  //     // print(guige['select_guiges'][i]['values']);
  //     List<String> x = [];
  //     for (var j = 0; j < guige['select_guiges'][i]['values'].length; j++) {
  //       x.add(guige['select_guiges'][i]['values'][j]['value'].toString());
  //     }
  //     col.add(Align(
  //       child: Text(guige['select_guiges'][i]['name']),
  //       alignment: Alignment.topLeft,
  //     )); // 规格名称
  //     col.add(GroupButton(
  //         isRadio: true,
  //         spacing: 10,
  //         onSelected: (index, isSelected) {
  //           int n = -1;
  //           if (panduan.contains(guige['select_guiges'][i]['name'])) {
  //             for (var x = 0; x < names.length; x++) {
  //               var ttt = names[x][guige['select_guiges'][i]['name']];
  //               if (ttt != null && ttt != "") {
  //                 n = x;
  //                 break;
  //               }
  //             }
  //           }
  //           int xiabiao = int.parse('$index');
  //           if (n == -1) {
  //             // true
  //             panduan.add(guige['select_guiges'][i]['name']);
  //             params.add(xiabiao);
  //             names.add({
  //               guige['select_guiges'][i]['name']: guige['select_guiges'][i]
  //               ['values'][xiabiao]['value']
  //             });
  //           } else {
  //             params[n] = xiabiao;
  //             names[n][guige['select_guiges'][i]['name']] =
  //             guige['select_guiges'][i]['values'][xiabiao]['value'];
  //           }
  //           if (params.length == guige['select_guiges'].length) {
  //             if (params.length == 1) {
  //               money = double.parse(guige['values'][params[0]]['jiage']);
  //             } else if (params.length == 2) {
  //               money = double.parse(
  //                   guige['values'][params[0]]['children'][params[1]]['jiage']);
  //             } else {
  //               money = double.parse(guige['values'][params[0]]['children']
  //               [params[1]]['children'][params[2]]['jiage']);
  //             }
  //             print("规格金额：" + money.toString());
  //           }
  //           // 此处更新显示的规格价格
  //           funCb(() {});
  //         },
  //         buttons: x));
  //   }
  //   return Container(
  //     child: Column(children: col),
  //   );
  // }
}
